#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <e_file.h>
#include <string.h>
#define FILENAME "/tmp/out"
#define BUFSIZE 128

int mydaemon(void);
int main(int argc, char **argv)
{
	FILE *fp;
	time_t tm;
	struct tm *tmp;
	char buf[BUFSIZE] = {};
	//守护进程
	if (-1 == mydaemon()){
		exit (-1);
	}
	//
	fp = fopen (FILENAME, "w");
	if (NULL == fp)
	{
		perror ("fopen()");
		return -1;
	}
	while(1){
		time (&tm);
		tmp = localtime(&tm);
		if (NULL == tmp){
			perror("localtime()");
			exit(0);
		}
		memset(buf,0,BUFSIZE);
		strftime (buf, BUFSIZE, "%Y/%m/%d %H:%M:%S\n", tmp);
		fputs(buf, fp);
		fflush(NULL);
		sleep(1);
	}
	fclose(fp);
	return 0;
}

int mydaemon (void)
{
	pid_t pid;
	pid = fork();
	if (pid == -1){
		perror("fork()");
	}
	//直接让父进程终止
	if (pid > 0) {
		exit (0);
	}
	//子进程
	if (-1 == setsid()){
		perror("setsid()");
		return -1;
	}
	//pid==pgid==sid 脱离终端控制，是产生守护进程的必要条件
	umask (0);
	chdir ("/");
	int fd = open ("/dev/null",O_RDWR);
	if (-1 == fd){
		perror ("open()");
		return -1;
	}
	dup2 (0, fd);
	dup2 (1, fd);
	dup2 (2, fd);
	if (fd > 2){
		close (fd);
	}
	return 0;
}

